package com.allwees.bs.c.module.order.entity;

import com.allwees.bs.core.model.order.entity.OrderItemModel;
import com.allwees.bs.core.model.order.wf.order.EOrderItemAction;
import com.allwees.bs.core.model.order.wf.order.EOrderItemState;
import com.allwees.core.wf.Workflow;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import java.util.Date;

@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@Entity
@Table(name = "o_order_item")
public class OrderItemEntity extends OrderItemModel implements Workflow<EOrderItemState, EOrderItemAction> {

    // 评论过期时间
    private Date reviewExpiredAt;

    // 收货后退货过期时间
    private Date refundExpiredAt;

    @Column(columnDefinition = "varchar(255)")
    @Enumerated(EnumType.STRING)
    private EOrderItemAction latestAction;

    @Column(columnDefinition = "varchar(255)")
    @Enumerated(EnumType.STRING)
    private EOrderItemState backState;

    @Column(columnDefinition = "varchar(255)")
    @Enumerated(EnumType.STRING)
    private EOrderItemState state;


    private String defNo;

    /**
     * 是否可退货
     */
    protected Boolean refundAble;


    public boolean realReviewAble() {
        if(refunded != null && refunded){
            return false;
        }
        // 已评论 或者已退货
        if (getReviewAt() != null || getApplyRefundAt() != null ) {
            return false;
        }
        if (getReviewExpiredAt() == null) {
            return false;
        }
        // 已过期
        return System.currentTimeMillis() <= getReviewExpiredAt().getTime();
    }

    public boolean realRefundAble() {
        if (refundAble != null) {
            return refundAble;
        }
        if(refunded != null && refunded){
            return false;
        }
        if(state != null && !(EOrderItemState.WAIT_SHIP.equals(state) || EOrderItemState.RECEIVED.equals(state))){
            return false;
        }

        if(EOrderItemState.WAIT_SHIP.equals(state) && getCanShipping()){
            return false;
        }

        // 已评论 或者已退货
        if (getReviewAt() != null || getApplyRefundAt() != null) {
            return false;
        }
        // 已过期
        return System.currentTimeMillis() <= getRefundExpiredAt().getTime();
    }

    @Override
    public String getBsKey() {
        return uuid;
    }
}
